<?php

namespace App\Http\Controllers\Client\Activity;

use App\Http\Controllers\ClientController;
use App\Jobs\LotteryApplyJob;
use App\Jobs\LotteryDraw;
use App\Jobs\LotteryDrawOvertime;
use App\Models\Activity;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ActivityCreateController extends ClientController
{

    /**
     * 发布霸王餐
     */
    public function index()
    {

        $all = $this->all;
        // 验证参数
        try {
            if (!isset($all['shop_id'])) {
                throw new \Exception('缺少参数:shop_id');
            }
            if (!isset($all['goods_id'])) {
                throw new \Exception('缺少参数:goods_id');
            }
            $goods_message = DB::table('lottery_goods')->where('goods_id', '=', $all['goods_id'])->first();
            $shop_message = DB::table('shop')->where('shop_id', '=', $all['shop_id'])->first();
            $shop_message = json_decode(json_encode($shop_message), true);
            $goods_message = json_decode(json_encode($goods_message), true);
            if ($shop_message['we_id'] !== $this->we_id) {
                return $this->setReturnJson(-1, '您不是这个店铺的所有者，不能发布霸王餐');
            }
            if ($goods_message['creator'] !== $this->we_id) {
                return $this->setReturnJson(-1, '您不是该霸王餐活动策略的拥有者，不能使用此活动');
            }
            if ($goods_message['shop_id'] !== $shop_message['shop_id']) {
                return $this->setReturnJson(-1, '参数错误，霸王餐活动与店铺不对应');
            }
            // 检查当前店铺状态
            $verified = DB::table('shop')->where('shop_id','=',$all['shop_id'])->value('verified');
            if($verified != Data::DATA_DB_LAIFEI_SHOP_VERIFIED_SUCCESS){
                return $this->setReturnJson(-1,'当前店铺信息未审核通过，请重新编辑店铺并等待管理员审核');
            }
        } catch (\Exception $e) {
            Log::error(ActivityCreateController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '参数错误');
        }

        try {
            DB::beginTransaction();

            // 查询霸王餐余量
            $remaining = DB::table('lottery_remaining')
                ->where('we_id', '=', $this->we_id)
                ->where('st_id','=',$shop_message['shop_type'])
                ->lockForUpdate()
                ->first();
            $remaining = json_decode(json_encode($remaining), true);
            if (!$remaining || $remaining['remaining_times'] < 1) {
                DB::rollBack();
                return $this->setReturnJson(-1, '您购买的霸王餐次数余额不足');
            }
            $act_no = self::actNo();

            //新建活动
            $date = date('Y-m-d H:i:s');

            $end_time = date('Y-m-d H:i:s', time() + Period::getSetting('LOTTERY_PARTICIPATE_TIME')[$shop_message['shop_type']]);

            $act_id = DB::table('lottery_activity')
                ->insertGetId([
                    'act_no' => $act_no,
                    'goods_id' => $all['goods_id'],
                    'shop_id' => $all['shop_id'],
                    'start_time' => $date,
                    'end_time' => $end_time,
                    'is_stop' => 0,
                    'creator' => $this->we_id,
                ]);

            // 核销数量
            DB::table('lottery_remaining')
                ->where('lr_id', '=', $remaining['lr_id'])
                ->decrement('remaining_times');
            DB::table('lottery_remaining')
                ->where('lr_id', '=', $remaining['lr_id'])
                ->increment('in_use_times');
            // 记录核销日志
            DB::table('lottery_remaining_log')->insert([
                'lr_id' => $remaining['lr_id'],
                'action' => 2,//消费
                'action_num' => 1,
                'rest_num' => $remaining['remaining_times'] - 1,
                'in_use_num' => $remaining['in_use_times'] + 1,
            ]);

            // 加入队列：在$end_time截止活动并开奖
//            LotteryApplyJob::dispatch($act_id);
            LotteryDraw::dispatch($act_id)->delay(Activity::drawTime($end_time));
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(ActivityCreateController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '发布失败');
        }
        return $this->setReturnJson(0, '发布成功');

    }

    private function actNo()
    {
        $prefix = env("APP_ENV") === 'production' ? 'P' : 'T';//测试前缀T，生产前缀P
        $date = date('ymd');
        $maxNo = DB::table('lottery_activity')->where('act_no', 'like', $prefix . $date . '%')->latest()->value('act_no');
        if ($maxNo) {
            $no = substr($maxNo, 7);
            $no = (int)$no + 1;
            $no = str_pad((string)$no, 4, '0', STR_PAD_LEFT);
            $act_no = $date . $no;
        } else {
            $act_no = $date . '0001';
        }
        return $prefix . $act_no;
    }


}
